package net.qiyuesuo.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;

import net.qiyuesuo.pojo.FileMeta;
import net.qiyuesuo.service.AbstractService;
import net.qiyuesuo.service.FileMetaService;
import net.qiyuesuo.utils.file.FileUtils;

public class FileMetaLocalServiceImpl extends AbstractService implements FileMetaService {

	//文件元数据信息存储地址
	private String logPath = "C:\\Users\\Administrator\\Desktop\\File\\Logs\\metadata.txt"; 
	
	@Override
	public int saveInfo(FileMeta info) {
		Path path = Paths.get(logPath);
		FileOutputStream fos = null;
		try {
			if(!Files.exists(path, new LinkOption[]{ LinkOption.NOFOLLOW_LINKS})) {
				//文件不存在
				fos = new FileOutputStream(Files.createFile(path).toFile());
			}else {
				//文件已经存在，在文件末尾写入
				fos = new FileOutputStream(path.toFile(),true);
			}
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			osw.write(info.toJson());
			osw.write("\r\n");
			osw.close();
			logger.info("FileInfoService储存元数据：将uuid:"+info.getUuid()+"元数据存入文件"+logPath+"中");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 1;
	}

	@Override
	public int deleteInfo(String uuid) {
		 String str = FileUtils.getContentByPath(logPath);
		 String [] strs = str.split("\r\n");
		 String result = "";
		 for (String string : strs) {
			if(string.contains(uuid)) {
				continue;
			}
			result = result+string+"\r\n";
		 }
	     File logFile = new File(logPath);
	     try (FileOutputStream fos= new FileOutputStream(logFile);
	    	  OutputStreamWriter osw = new OutputStreamWriter(fos);
	    		 ){
			 osw.write(result);
			 osw.write("\r\n");
			 osw.close();
		 } catch (FileNotFoundException e) {
		 	 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
	     logger.info("删除uuid为："+uuid+"元数据信息");
	     return 1;
	}

	@Override
	public FileMeta getInfo(String uuid) {
		String info = null;
		String str = FileUtils.getContentByPath(logPath);
		//读取到文件之后，取出需要的数据
		String [] strs = str.split("\r\n");
		for (String string : strs) {
			if(string.contains(uuid)) {
				info = string.substring(2, string.length()-2).replaceAll("\"","");
			}
		}
		logger.info("获取文件元数据:"+info);
		return new FileMeta(info);
	}
}
